
<template>
  <div>
    <!-- 查看代码按钮 -->
    <el-button
      type="text"
      class="text-blue-600 hover:text-blue-800 text-sm flex items-center"
      @click="openDialog"
    >
      <i class="fa fa-code mr-1"></i>查看代码
    </el-button>

    <!-- 代码展示对话框 -->
    <el-dialog
      title="查看代码"
      v-model="dialogVisible"
      width="80%"
      :before-close="handleClose"
      append-to-body
    >
      <div class="code-container">
        <pre><code :class="`language-${language}`">{{ code }}</code></pre>
      </div>
      <template #footer>
        <el-button type="primary" @click="dialogVisible = false"
          >关闭</el-button
        >
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { ElButton, ElDialog } from "element-plus";
import hljs from "highlight.js";

// 定义 props
defineProps({
  code: {
    type: String,
    required: true,
  },
  language: {
    type: String,
    default: "javascript",
  },
});

// 控制对话框显示状态
const dialogVisible = ref(false);

// 打开对话框
const openDialog = () => {
  dialogVisible.value = true;
};

// 关闭对话框前的确认
const handleClose = (done) => {
  done(); // 直接关闭对话框
};

// 组件挂载时初始化代码高亮
onMounted(() => {
  document.querySelectorAll("pre code").forEach((block) => {
    hljs.highlightElement(block);
  });
});
</script>

<style scoped>
/* 代码容器样式 */
.code-container {
  max-height: 500px;
  overflow-y: auto;
  background: #1e1e1e; /* 深色背景，适合代码展示 */
  padding: 16px;
  border-radius: 4px;
}

/* 确保代码块样式 */
pre code {
  display: block;
  font-family: "Consolas", "Monaco", monospace;
  font-size: 14px;
  line-height: 1.5;
}
</style>
